<?php

declare(strict_types=1);

namespace App\Model;

use Hyperf\DbConnection\Model\Model;
use Hyperf\DbConnection\Db;

/**
 * 用户关注
 */
class UserFollow extends Model
{
    protected $table = 'user_follow';

    protected $fillable = [
        'user_id', 'followed_user_id', 'flag'
    ];

    public function userItem()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    /**
     * 用户userId是否关注followedUserId
     */
    static function check($userId = 0, $followedUserId = 0)
    {
        $where = [
            'user_id' => $userId,
            'followed_user_id' => $followedUserId,
            'flag' => 1
        ];
        return self::where($where)->count() ? 1 : 0;
    }

    /**
     * 添加关注
     */
    static function addFollow($userId = 0, $followedUserId = 0, $flag = 1)
    {
        $ret = self::updateOrCreate([
            'user_id' => $userId,
            'followed_user_id' => $followedUserId,
        ], [
            'user_id' => $userId,
            'followed_user_id' => $followedUserId,
            'flag' => $flag
        ]);
        return $ret ? 1 : 0;
    }

    /**
     * 获取关注数量
     */
    static function getFollowNum($userId = 0)
    {
        $where = [
            'user_id' => $userId,
            'flag' => 1
        ];
        return self::where($where)->count();
    }

    /**
     * 获取粉丝数量
     */
    static function getFansNum($userId = 0)
    {
        $where = [
            'followed_user_id' => $userId,
            'flag' => 1
        ];
        return self::where($where)->count();
    }

    /**
     * 获取关注列表
     */
    static function getFollowList($userId = 0)
    {
        $where = [
            'user_id' => $userId,
            'flag' => 1
        ];
        return self::where($where)->orderBy('id', 'desc')->pluck('followed_user_id')->toArray();
    }

    /**
     * 获取粉丝列表
     */
    static function getFansList($userId = 0)
    {
        $where = [
            'followed_user_id' => $userId,
            'flag' => 1
        ];
        return self::where($where)->orderBy('updated_at', 'desc')->pluck('user_id')->toArray();
    }
}
